﻿using FlyingEye.Devices;
using FlyingEye.Devices.Repositories;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Guids;
using Volo.Abp.Uow;

namespace FlyingEye.DeviceAppService
{
    public class DeviceAppServiceDataSeedContributor : IDataSeedContributor, ITransientDependency
    {

        private readonly IGuidGenerator _guidGenerator;

        private readonly IDeviceClientRepository _deviceClientRepository;

        private readonly IDeviceConfigurationRepository _deviceConfigurationRepository;

        public DeviceAppServiceDataSeedContributor(
            IGuidGenerator guid,
            IDeviceClientRepository deviceClientRepository,
            IDeviceConfigurationRepository deviceConfigurationRepository)
        {
            _guidGenerator = guid;
            _deviceClientRepository = deviceClientRepository;
            _deviceConfigurationRepository = deviceConfigurationRepository;
        }

        [UnitOfWork]
        public async Task SeedAsync(DataSeedContext context)
        {
            await CreateDeviceClientAsync();
            await CreateDeviceConfigurationAsync();
        }

        public async Task CreateDeviceClientAsync()
        {
            var model = await _deviceClientRepository.FindAsync(item => item.Id == "TestDeviceClient");

            if (model == null)
            {
                await _deviceClientRepository.InsertAsync(new Devices.DeviceClientModel(
                    "TestDeviceClient",
                    9999,
                    "TestProcessName",
                    null!));
            }
        }

        public async Task CreateDeviceConfigurationAsync()
        {
            var model = await _deviceConfigurationRepository.FindAsync(item => item.ResourceId == "TestDeviceClient");

            if (model == null)
            {
                await _deviceConfigurationRepository.InsertAsync(new Devices.DeviceConfigurationModel(
                    _guidGenerator.Create(),
                    "TestDeviceClient",
                    "TestDeviceName",
                    "127.0.0.1",
                    13666,
                    PlcTypes.SiemensS1500,
                    null,
                    null));
            }
        }
    }
}
